package io.renren.modules.sp.controller.front;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RenException;
import io.renren.common.redis.RedisUtils;
import io.renren.common.sms.AliyunSms;
import io.renren.common.utils.*;
import io.renren.modules.sp.dto.SpMatchItemTeamUserDTO;
import io.renren.modules.sp.dto.SpUserDTO;
import io.renren.modules.sp.dto.SpUserScoreDTO;
import io.renren.modules.sp.entity.*;
import io.renren.modules.sp.service.*;
import io.swagger.annotations.Api;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;


/**
* 用户
*
* @author whc 15953295779@126.com
* @since 3.0 2023-04-21
*/
@RestController
@RequestMapping("front/spuser")
@Api(tags="用户")
public class FrontUserController extends FrontBaseController {
    @Autowired
    private SpUserService spUserService;
    @Autowired
    private CheckCodeUtils checkCodeUtils;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SpTeamService spTeamService;
    @Autowired
    private SpTeamUserService spTeamUserService;
    @Autowired
    private SpMatchItemTeamService spMatchItemTeamService;
    @Autowired
    private SpMatchItemTeamUserService spMatchItemTeamUserService;

    @Autowired
    private SpUserScoreService spUserScoreService;
    @Autowired
    private SpMatchItemService spMatchItemService;
    @Autowired
    private SpBaseMatchItemService spBaseMatchItemService;
    @Autowired
    private SpMatchService spMatchService;

    @Value("${aliyun.sms.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyun.sms.accessSecret}")
    private String accessSecret;

    @Value("${aliyun.sms.templateCode}")
    private String templateCode;

    @Value("${aliyun.sms.signName}")
    private String signName;

    /**
     * 登录
     */
    @PostMapping("login")
    public Result<SpUserDTO> login(@RequestBody SpUserDTO loginInfo) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("account", loginInfo.getAccount());

        // 判断验证码是否正确
        if (!checkCodeUtils.verifyCheckCode(loginInfo.getAccount(), loginInfo.getVerificationCode())) {
            return new Result<SpUserDTO>().error("验证码错误,请重新获取");
        }

        List<SpUserDTO> userList = spUserService.list(param);
        if (userList.size() == 0) {
            return new Result<SpUserDTO>().error("账号或密码错误");
        }
        /*if(!userList.get(0).getPassword().equals(MD5Util.computeMD5(loginInfo.getPassword()))){
            return new Result<SpUserDTO>().error("账号或密码错误");
        }*/
        String token = UUID.randomUUID().toString().replace("-", "");
        SpUserDTO userInfo = userList.get(0);

        // 选手老师不放开登录
        /*if("2".equals(userInfo.getRoleId()) || "3".equals(userInfo.getRoleId())){
            return new Result<SpUserDTO>().error("选手和老师暂不开放登录");
        }*/
        String key = "USER:" + token;
        userInfo.setToken(token);

        String url = "";
        SpUserDTO returnDto = userList.get(0);
        String roleIds = userInfo.getRoleId();
        //负责人是否有队伍，默认无队伍
        int leaderHasTeam = 0;
        //判断是否有代表队
        List<SpTeamEntity> list = new ArrayList<>();
        //代表队负责人登录时
        if (roleIds.contains("0")) {
            list = spTeamService.queryList(
                    new QueryWrapper<SpTeamEntity>()
                            .eq("creator", returnDto.getId())
            );
            //代表队负责人登录时，把主领队踢下线
            if (list != null && list.size() > 0) {
                // 负责人带的有队
                leaderHasTeam = 1;
                spTeamUserService.queryList(
                        new QueryWrapper<SpTeamUserEntity>()
                                .eq("team_id", list.get(0).getId())
                                .eq("type", "1")
                ).forEach(spTeamUserEntity -> {
                    SpUserEntity userEntity = spUserService.selectById(spTeamUserEntity.getUserId());
                    if (userEntity != null) {
                        redisUtils.delete("TOKEN:" + userEntity.getAccount());
                    }
                });
            }
        }
        // 负责人没有队伍的时候，进行领队校验
        if (roleIds.contains("1") && leaderHasTeam == 0) {
            List<SpTeamUserEntity> teamList = spTeamUserService.queryList(
                    new QueryWrapper<SpTeamUserEntity>()
                            .eq("user_id", returnDto.getId())
                            .eq("type", "1") //1领队
            );
            if (teamList != null && teamList.size() > 0) {
                list = spTeamService.queryList(
                        new QueryWrapper<SpTeamEntity>()
                                .eq("id", teamList.get(0).getTeamId())
                );
                // 主领队登录时，把代表队负责人踢下线
                if (list != null && list.size() > 0) {
                    // 设置主领队标识
                    returnDto.setIsMainLeader(1);
                    SpUserEntity userEntity = spUserService.selectById(list.get(0).getCreator());
                    if (userEntity != null) {
                        redisUtils.delete("TOKEN:" + userEntity.getAccount());
                    }
                }

            } else {
                url = "/info";
            }
        }

        /**
         用户类型：负责人+领队
             ① 负责人有队伍，是当前队伍的副领队
                直接进入系统
             ② 负责人有队伍，是当前队伍的主领队
                直接进入系统
             ③ 负责人没队伍 + 其他队伍的主领队
                直接进入系统
             ④ 负责人没队伍 + 其他队伍的副领队
                创建队伍，提示解绑
             ⑤负责人没队伍 + 也不是主领队和副领队
                跳转到创建队伍
         用户类型： 领队
             ① 领队是主领队
                跳转到本队选手
             ② 领队是副领队
                个人信息
         */
        if (list != null && list.size() > 0) {
            SpTeamEntity spTeamEntity = list.get(0);
            userInfo.setTeamId(list.get(0).getId());
            userInfo.setProvince(spTeamEntity.getProvince());
            userInfo.setCity(spTeamEntity.getCity());
            // 主领队跳转到本队选手
            if (returnDto.getIsMainLeader() != null && returnDto.getIsMainLeader() == 1) {
                url = "/player";
            } else {
                url = "/team/index";
            }
        } else {
            // 代表队负责人跳转到创建代表队页面，其他账号跳转到个人中心
            if (roleIds.contains("0")) {
                url = "/account/team";
            } else {
                url = "/info";
            }
        }
        //查询是否有代表队
        Map<String, Object> userMap = null;
        if(roleIds.contains("0")){
            userMap = spTeamService.queryTeamInfoByCreator(userInfo.getId());
            if(userMap.isEmpty()){
                userMap = spUserService.queryUserById(userInfo.getId());
            }
        }else{
            userMap = spUserService.queryUserById(userInfo.getId());
        }

        userInfo.setSpTeamEntity(userMap != null ? userMap : null);
        if (userMap != null) {
            userInfo.setTeamId((Long) userMap.get("teamId"));
        }

        //如果是老师或者选手，跳转到个人中心，代表队负责人跳转到代表队信息
        if (!(roleIds.contains("0") || roleIds.contains("1"))
                && (roleIds.contains("2") || roleIds.contains("3"))) {
            url = "/info";
        }
        //登录有效期半个小时
        redisUtils.set(key, JSONObject.toJSONString(userInfo), 3600L);
        String tokenKey = "TOKEN:" + userInfo.getAccount();
        //登录有效期半个小时
        redisUtils.set(tokenKey, userInfo.getToken(), 3600L);

        //获取登录类型
        String loginType = loginInfo.getLoginType();
        //跳转移动端页面
        if ("wap".equals(loginType)) {
            url = "/wap" + url;
        }
        returnDto.setUrl(url);
        return new Result<SpUserDTO>().ok(returnDto);
    }

    /**
     * 注册
     * 场景：领队注册、指导老师、选手注册
     * 页面改造： 注册时需要指定身份 领队、指导老师、选手
     *
     * @param loginInfo
     * @return
     */
    @PostMapping("register")
    public Result<SpUserDTO> register(@RequestBody SpUserDTO loginInfo) {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("phone", loginInfo.getPhone());

        // 判断验证码是否正确
        if (!checkCodeUtils.verifyCheckCode(loginInfo.getPhone(), loginInfo.getPassword())) {
            return new Result<SpUserDTO>().error("验证码错误,请重新获取");
        }

        //已经注册过的账号再次注册，只需要添加角色
        if (loginInfo.getId() != null) {
            SpUserEntity userDto = spUserService.selectById(loginInfo.getId());
            if (userDto != null) {
                String roleIds = loginInfo.getRoleId();
                String userRoleIds = userDto.getRoleId();
                //判断角色有没有添加
                if (roleIds.split(",").length > userRoleIds.split(",").length) {
                    // 当用户同时具有负责人+领队属性时，不需要校检是否在代表队中任职，可以直接增补
                    if(userRoleIds.contains("0") && userRoleIds.contains("1")){
                        userDto.setRoleId(loginInfo.getRoleId());
                        spUserService.updateById(userDto);
                    }else {
                        // 判断当前用户是否已经作为领队挂在代表队
                        List<SpTeamUserEntity> teamList = spTeamUserService.queryList(
                                new QueryWrapper<SpTeamUserEntity>()
                                        .eq("user_id", loginInfo.getId())
                                        .in("type", Arrays.asList("1", "2"))
                        );
                        if (teamList != null && teamList.size() > 0) {
                            return new Result<SpUserDTO>().error("请先从代表队中解除领队职务，再进行用户类型增补");
                        }
                        userDto.setRoleId(loginInfo.getRoleId());
                        spUserService.updateById(userDto);
                    }
                } else {
                    return new Result<SpUserDTO>().error("账号已存在");
                }
                return new Result<SpUserDTO>().ok(loginInfo);
            }
            return new Result<SpUserDTO>().ok(loginInfo);
        } else {
            // 校验身份证是否已经注册过
            Map<String, Object> param2 = new HashMap<String, Object>();
            param2.put("idCard", loginInfo.getIdCard());
            List<SpUserDTO> userList2 = spUserService.list(param2);
            if (userList2.size() > 0) {
                return new Result<SpUserDTO>().error("身份证已经注册过");
            }

            // 校验手机号是否已经注册过
            Map<String, Object> param3 = new HashMap<String, Object>();
            param3.put("phone", loginInfo.getPhone());
            List<SpUserDTO> userList3 = spUserService.list(param3);
            if (userList3.size() > 0) {
                return new Result<SpUserDTO>().error("手机号已经注册过");
            }

            loginInfo.setAccount(loginInfo.getPhone());
            loginInfo.setCreateAt(new Date());
            spUserService.checkInfo(loginInfo);
            spUserService.save(loginInfo);
            return new Result<SpUserDTO>().ok(loginInfo);
        }
    }

    /**
     * 获取短信验证码
     *
     * @param params
     * @return
     */
    @PostMapping("/getCheckCode")
    @ResponseBody
    public Result getCheckCode(@RequestBody Map<String, Object> params) {
        /*final String account = "LTAI5tLW1R2NtBqvoBGD5m8D";
        final String password = "1ga3wpQQilDOAoJaUmMP4QI96JKxhP";
        // 国内短信模板
        final String templateCode = "SMS_276510483";
        final String signName = "全国青少年无人机大赛";
        // 国际短信模板
        final String templateCode2 = "SMS_461560096";
        final String signName2 = "全国青少年无人机大赛港澳";*/

        String oldmobile = (String) params.get("phone");
        // 国际区号
        String code = (String) params.get("code");
        // 区号为空，默认为国内
        if (StringUtils.isBlank(code)) {
            code = "86";
        }
        String mobile = oldmobile.trim();
        String checkCode = "";
        if ("86".equals(code)) {
            checkCode = AliyunSms.sendCheckCode(accessKeyId, accessSecret, mobile, templateCode, signName);
        } else if ("852".equals(code)) {
            // 香港
            checkCode = AliyunSms.sendCheckCode(accessKeyId, accessSecret, mobile, templateCode, signName);
        } else if ("853".equals(code)) {
            // 澳门
            checkCode = AliyunSms.sendCheckCode(accessKeyId, accessSecret, mobile, templateCode, signName);
        }

        if (StringUtils.isNotBlank(checkCode)) {
            System.out.println("验证码为：" + checkCode);
            // 将验证码放入缓存中
            redisUtils.set(mobile, checkCode, 60 * 5);
            Map<String, Object> map = new HashMap<>(16);
            map.put("msg", "短信发送成功");
            return new Result().ok(map);
        } else {
            return new Result().error("短信发送失败,请检查手机号格式");
        }
    }


    /**
     * 查询用户信息
     *
     * @param loginInfo
     * @return
     */
    @PostMapping("queryUser")
    public Result<SpUserEntity> queryUser(@RequestBody SpUserDTO loginInfo, HttpServletRequest request) {
        SpUserDTO currentUser = this.getFrontUserInfo(request);

        if (currentUser == null) {
            return new Result<SpUserEntity>().error("请先登录");
        }
        return spUserService.queryUser(loginInfo);
    }

    /**
     * 根据手机号查询用户
     *
     * @param loginInfo
     * @return
     */
    @PostMapping("queryUserByPhone")
    public Result<SpUserEntity> queryUserByPhone(@RequestBody SpUserDTO loginInfo) {
        QueryWrapper<SpUserEntity> queryWrapper = new QueryWrapper<SpUserEntity>();
        queryWrapper.eq("phone", loginInfo.getPhone());
        List<SpUserEntity> userList = spUserService.queryList(queryWrapper);
        if (userList.size() > 0) {
            return new Result<SpUserEntity>().ok(userList.get(0));
        } else {
            return new Result<SpUserEntity>().error("用户信息不正确");
        }
    }

    /**
     * 查询代表队负责人
     * @param loginInfo
     * @return
     */
    @PostMapping("queryTeamByPhone")
    public Result<Map<String,Object>> queryTeamByPhone(@RequestBody SpUserDTO loginInfo) {
        Map<String,Object> teamInfo = spTeamService.queryTeamInfoByPhone(loginInfo.getPhone());
        if (teamInfo!= null) {
            return new Result<Map<String,Object>>().ok(teamInfo);
        } else {
            return new Result<Map<String,Object>>().error("用户信息不正确");
        }
    }

    /**
     * 查询代表队用户身份
     * @param loginInfo
     * @return
     */
    @PostMapping("queryTeamUserByPhone")
    public Result<SpTeamUserEntity> queryTeamUserByPhone(@RequestBody SpUserDTO loginInfo) {
        QueryWrapper<SpTeamUserEntity> queryWrapper = new QueryWrapper<SpTeamUserEntity>();
        queryWrapper.eq("phone", loginInfo.getPhone());
        queryWrapper.eq("type", "1");
        List<SpTeamUserEntity> userList = spTeamUserService.queryList(queryWrapper);
        spTeamService.queryTeamInfoByPhone(loginInfo.getPhone());
        if (userList.size() > 0) {
            return new Result<SpTeamUserEntity>().ok(userList.get(0));
        } else {
            return new Result<SpTeamUserEntity>().error("用户信息不正确");
        }
    }



    /**
     * 修改用户信息
     *
     * @param loginInfo
     * @return
     */
    @PostMapping("update")
    public Result<SpUserDTO> update(@RequestBody SpUserDTO loginInfo) {
        //此处校验有问题，不能开启，否则会导致修改身份证号码时，提示身份证号码已存在
        //spUserService.checkInfo(loginInfo);

        boolean result = MobilePhoneUtils.isMobilePhone(loginInfo.getPhone());
        if (!result) {
            return new Result<SpUserDTO>().error("手机号格式不正确，请检查");
        }

        //查询手机号是否已经注册其他账号
        QueryWrapper<SpUserEntity> queryWrapper = new QueryWrapper<SpUserEntity>();
        queryWrapper.eq("phone", loginInfo.getPhone());
        queryWrapper.ne("id", loginInfo.getId());
        List<SpUserEntity> userList = spUserService.queryList(queryWrapper);
        if (userList.size() > 0) {
            return new Result<SpUserDTO>().error("手机号已经注册");
        }

        // 输入的有验证码表示更换了手机号
        if (StringUtils.isNotEmpty(loginInfo.getPassword())) {
            // 判断验证码是否正确
            if (!checkCodeUtils.verifyCheckCode(loginInfo.getPhone(), loginInfo.getPassword())) {
                return new Result<SpUserDTO>().error("验证码错误,请重新获取");
            }
        } else {
            //没有验证码表示没有更换手机号
            loginInfo.setPhone(null);
        }

        //验证单位是否存在
        // 6.19日去掉
       /* String roleIds = loginInfo.getRoleId();
        if (roleIds.contains("0")) {
            boolean isCompany = QccUtil.isCompany(loginInfo.getCompany());
            if (!isCompany) {
                return new Result<SpUserDTO>().error("单位信息不存在");
            }
        }*/

        //修改用户信息
        if (StringUtils.isNotEmpty(loginInfo.getPhone())) {
            loginInfo.setAccount(loginInfo.getPhone());
        }
        spUserService.update(loginInfo);
        return new Result<SpUserDTO>().ok(loginInfo);
    }

    /**
     * 查询个人信息
     */
    @PostMapping("queryInfo")
    public Result<SpUserEntity> queryInfo(@RequestBody SpUserDTO spUserDTO) {
        SpUserEntity spUserEntity = spUserService.selectById(spUserDTO.getId());
        return new Result<SpUserEntity>().ok(spUserEntity);
    }

    /**
     * 退出登录
     */
    @PostMapping("logout")
    public Result logout(@RequestBody SpUserDTO loginInfo) {
        String key = "USER:" + loginInfo.getToken();
        redisUtils.delete(key);
        return new Result().ok("退出成功");
    }


    @GetMapping("{id}")
    public Result<SpUserEntity> queryUserById(@PathVariable("id") Long id, HttpServletRequest request) {
        SpUserEntity spUserEntity = spUserService.selectById(id);
        return new Result<SpUserEntity>().ok(spUserEntity);
    }

    @GetMapping("queryUserById")
    public Result<Map<String, Object>> queryUserById2(@RequestParam Long id, HttpServletRequest request) {
        Map<String, Object> spUserEntity = spUserService.queryUserById(id);
        return new Result<Map<String, Object>>().ok(spUserEntity);
    }

    /**
     * 修改授权书
     */
    @PostMapping("updateEmpower")
    public Result<SpUserEntity> updateEmpower(@RequestBody SpUserDTO loginInfo) {
        SpUserEntity user = new SpUserEntity();
        user.setId(loginInfo.getId());
        user.setEmpower(loginInfo.getEmpower());
        spUserService.updateById(user);
        return new Result<SpUserEntity>().ok(user);
    }

    /**
     * 验证用户是否已经注册
     *
     * @param loginInfo
     * @param request
     * @return
     */
    @PostMapping("registerValidate")
    public Result<SpUserEntity> registerValidate(@RequestBody SpUserDTO loginInfo, HttpServletRequest request) {
        SpUserDTO currentUser = this.getFrontUserInfo(request);

        // 判断验证码是否正确
        if (!checkCodeUtils.verifyCheckCode(loginInfo.getPhone(), loginInfo.getPassword())) {
            return new Result<SpUserEntity>().error("验证码错误,请重新获取");
        }

        QueryWrapper<SpUserEntity> queryWrapper = new QueryWrapper<SpUserEntity>();
        queryWrapper.eq("phone", loginInfo.getPhone());
        queryWrapper.eq("real_name", loginInfo.getRealName());
        List<SpUserEntity> userList = spUserService.queryList(queryWrapper);
        if (userList != null && userList.size() > 0) {
            return new Result<SpUserEntity>().ok(userList.get(0));
        }
        return new Result<SpUserEntity>().ok(null);
    }


    @PostMapping("queryCertificateBy")
    public Result<List<Map<String, Object>>> queryCertificateBy(@RequestBody Map<String, Object> params) {
        String type = "1"; // 1学生  2老师
        String realName = (String) params.get("realName");
        String idCard = (String) params.get("idCard");
        String certificate = (String) params.get("certificate");
        int count = 0;
        if (StringUtils.isNotBlank(realName)) {
            count++;
        }
        if (StringUtils.isNotBlank(idCard)) {
            count++;
            List<SpUserEntity> userList = spUserService.queryList(new QueryWrapper<SpUserEntity>().eq("id_card", idCard));
            if (userList != null && userList.size() > 0) {
                String roids = userList.get(0).getRoleId();
                if (roids.contains("2")) {
                    type = "2";
                }
            }
        }
        if (StringUtils.isNotBlank(certificate)) {
            count++;
            if (certificate.contains("T")) {
                type = "2";
            } else {
                type = "1";
            }
        }
        // 姓名、身份证、证书编号至少选择2项
        if (count < 2) {
            throw new RenException("姓名、身份证、证书编号至少选择两项");
        }
        List<Map<String, Object>> list = null;
        if ("2".equals(type)) {
            list = spMatchItemTeamService.queryTeacherCerBy(params);
        } else {
            list = spMatchItemTeamService.queryStudentCerBy(params);
        }
        Result<List<Map<String, Object>>> result = new Result<List<Map<String, Object>>>();
        result.ok(list);
        result.setMsg(type);
        return result;
    }

    /**
     * 查询证书图片
     */
    @GetMapping("t/{ticket}")
    public void queryCertificatePic(@PathVariable("ticket") String ticket, HttpServletResponse response) throws IOException {
        Map<String, Object> params = new HashMap<>();
        params.put("certificate", ticket);
        List<Map<String, Object>> list = spMatchItemTeamService.queryStudentCerBy(params);
        if (list.size() == 0) {
            System.out.println("证书不存在");
            return;
        }
        String realName = (String) list.get(0).get("realName");
        realName = URLEncoder.encode(realName, "UTF-8");
        String idCard = (String) list.get(0).get("idCard");
        String url = "http://login.int-ede.com/#/wap/certificate_student?realName=" + realName + "&idCard=" + idCard;
        response.sendRedirect(url);
    }

    /**
     * 查询证书图片
     */
    @GetMapping("tr/{ticket}")
    public void queryCertificateTeacherPic(@PathVariable("ticket") String ticket, HttpServletResponse response) throws IOException {
        List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserService.queryTicketBy(
                new QueryWrapper<SpMatchItemTeamUserEntity>().eq("certificate", ticket)
        );
        if (list.size() == 0) {
            System.out.println("证书不存在");
            return;
        }
        //查询用户信息
        SpUserEntity userEntity = spUserService.selectById(list.get(0).getUserId());
        String realName = userEntity.getRealName();
        realName = URLEncoder.encode(realName, "UTF-8");
        String idCard = userEntity.getIdCard();
        String url = "http://login.int-ede.com/#/wap/certificate_teacher?realName=" + realName + "&idCard=" + idCard;
        response.sendRedirect(url);
    }


    /**
     * 修改用户类型
     *
     * @param phone：手机号
     * @param roleId：用户类型，逗号隔开
     */
    @GetMapping("updateUserType")
    public Result<String> updateUserType(@RequestParam String phone, String roleId) {
        return spUserService.updateUserType(phone, roleId);
    }

    @GetMapping("queryTicket")
    public Result<String> queryTicket(@RequestParam String matchId, String userId) {
        String pic = spMatchItemTeamUserService.queryTicketByUserId(Long.parseLong(matchId), Long.parseLong(userId));
        return new Result<String>().ok(pic);
    }

    /**
     * 升级成指导老师
     */
    @GetMapping("upgradeTeacher")
    public Result<String> upgradeTeacher(@RequestParam Long id, String password) {
        return spUserService.upgradeTeacher(id, password);
    }

    /**
     * 增补指导老师权限
     */
    @GetMapping("addTeacherUserType")
    public Result<String> addTeacherUserType(@RequestParam Long id, String password) {
        return spUserService.addTeacherUserType(id, password);
    }

    /**
     * 校验公司名称
     * */
    @GetMapping("checkCompany")
    public Result<String> checkCompany(@RequestParam String company) {
        List<SpTeamEntity> list = spTeamService.isExistCompany(company);
        if (list != null && list.size() > 0) {
            return new Result<String>().ok("该单位已注册代表队");
        }
        return new Result<String>().error("该单位尚未注册代表队，请确认单位信息");
    }


    /**
     * 根据手机号查询用户
     * @param id
     * @return
     */
    @GetMapping("queryUserByTeamUserId")
    public Result<HashMap<String,Object>> queryUserByTeamUserId(@RequestParam String id, String type) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        if("group".equals(type)){
            SpMatchItemTeamEntity matchItemTeamEntity = spMatchItemTeamService.selectById(id);
            if (matchItemTeamEntity != null) {
                map.put("matchItemTeamId", matchItemTeamEntity.getId());
                map.put("groupId", matchItemTeamEntity.getGroupId());
                map.put("teamName", matchItemTeamEntity.getTeamName());
                SpMatchItemEntity matchItemEntity = spMatchItemService.selectById(matchItemTeamEntity.getMatchItemId());
                if (matchItemEntity != null) {
                    SpBaseMatchItemEntity baseMatchItemEntity = spBaseMatchItemService.selectById(matchItemEntity.getBaseMatchItemId());
                    if (baseMatchItemEntity != null) {
                        map.put("matchItemName", baseMatchItemEntity.getItemName());
                    }
                    SpMatchEntity matchEntity = spMatchService.selectById(matchItemEntity.getMatchId());
                    if (matchEntity != null) {
                        map.put("matchName", matchEntity.getMatchName());
                    }
                }
                // 查询分数
                List<SpUserScoreEntity> list = spUserScoreService.queryBy(
                        new QueryWrapper<SpUserScoreEntity>()
                                .eq("team_user_id", id)
                                .orderByDesc("id")
                );
                if(list!=null && list.size()>0){
                    map.put("scoring", list.get(0));
                }
                return new Result<HashMap<String, Object>>().ok(map);
            }else{
                return new Result<HashMap<String, Object>>().error("参赛信息不存在");
            }
        }else{
            SpMatchItemTeamUserEntity userEntity = spMatchItemTeamUserService.selectById(id);
            if (userEntity != null) {
                map.put("score", userEntity.getScore());
                map.put("score1", userEntity.getScore1());
                map.put("score2", userEntity.getScore2());
                Long userId = userEntity.getUserId();
                SpUserEntity userInfo = spUserService.selectById(userId);
                if (userInfo != null) {
                    map.put("userId", userInfo.getId());
                    map.put("userName", userInfo.getRealName());
                    map.put("company", userInfo.getCompany());
                }
                SpMatchItemTeamEntity matchItemTeamEntity = spMatchItemTeamService.selectById(userEntity.getMatchItemTeamId());
                if (matchItemTeamEntity != null) {
                    map.put("matchItemTeamId", matchItemTeamEntity.getId());
                    map.put("groupId", matchItemTeamEntity.getGroupId());
                    SpMatchItemEntity matchItemEntity = spMatchItemService.selectById(matchItemTeamEntity.getMatchItemId());
                    if (matchItemEntity != null) {
                        SpBaseMatchItemEntity baseMatchItemEntity = spBaseMatchItemService.selectById(matchItemEntity.getBaseMatchItemId());
                        if (baseMatchItemEntity != null) {
                            map.put("matchItemName", baseMatchItemEntity.getItemName());
                        }
                        SpMatchEntity matchEntity = spMatchService.selectById(matchItemEntity.getMatchId());
                        if (matchEntity != null) {
                            map.put("matchName", matchEntity.getMatchName());
                        }
                    }
                }
                // 查询分数
                List<SpUserScoreEntity> list = spUserScoreService.queryBy(
                        new QueryWrapper<SpUserScoreEntity>()
                                .eq("team_user_id", id)
                                .orderByDesc("id")
                );
                if(list!=null && list.size()>0){
                    map.put("scoring", list.get(0));
                }
                return new Result<HashMap<String, Object>>().ok(map);
            } else {
                return new Result<HashMap<String, Object>>().error("参赛信息不存在");
            }
        }

    }

    /**
     * 保存成绩
     */
    @PostMapping("saveScore")
    public Result<String> saveScore(@RequestBody Map<String, Object> params) {
        try {
            SpUserScoreDTO spUserScoreDTO = new SpUserScoreDTO();
            spUserScoreDTO.setTeamUserId(Integer.parseInt(params.get("id").toString()));
            //spUserScoreDTO.setUserId(Integer.parseInt(params.get("userId").toString()));
            spUserScoreDTO.setSite((String) params.get("site"));
            spUserScoreDTO.setMatchItemTeamId(Integer.parseInt(params.get("matchItemTeamId").toString()));
            spUserScoreDTO.setScore(params.get("score").toString());
            String seconds = (String) params.get("seconds");
            if (StringUtils.isNotBlank(seconds)) {
                if (seconds.contains("″")) {
                    seconds = seconds.replace("″", ".");
                }
                spUserScoreDTO.setSeconds(seconds);
            }
            String seconds2 = (String) params.get("seconds2");
            if (StringUtils.isNotBlank(seconds2)) {
                if (seconds2.contains("″")) {
                    seconds2 = seconds2.replace("″", ".");
                }
                spUserScoreDTO.setSeconds2(seconds2);
            }
            spUserScoreDTO.setAdd1(params.get("add1") + "");
            spUserScoreDTO.setAdd2(params.get("add2") + "");
            spUserScoreDTO.setAdd3(params.get("add3") + "");
            spUserScoreDTO.setAdd4(params.get("add4") + "");
            spUserScoreDTO.setAdd5(params.get("add5") + "");
            spUserScoreDTO.setAdd6(params.get("add6") + "");
            spUserScoreDTO.setAdd7(params.get("add7") + "");
            spUserScoreDTO.setAdd8(params.get("add8") + "");
            spUserScoreDTO.setAdd9(params.get("add9") + "");
            spUserScoreDTO.setAdd10(params.get("add10") + "");
            spUserScoreDTO.setSub1(params.get("sub1") + "");
            spUserScoreDTO.setSub2(params.get("sub2") + "");
            spUserScoreDTO.setSub3(params.get("sub3") + "");
            spUserScoreDTO.setSub4(params.get("sub4") + "");
            spUserScoreDTO.setSub5(params.get("sub5") + "");
            spUserScoreDTO.setSub6(params.get("sub6") + "");
            spUserScoreDTO.setSub7(params.get("sub7") + "");
            spUserScoreDTO.setSub8(params.get("sub8") + "");
            spUserScoreDTO.setSub9(params.get("sub9") + "");
            spUserScoreDTO.setSub10(params.get("sub10") + "");
            spUserScoreDTO.setMm(params.get("mm") + "");
            spUserScoreDTO.setSs(params.get("ss") + "");
            spUserScoreDTO.setMs(params.get("ms") + "");
            spUserScoreDTO.setAdd11(params.get("add11") + "");
            spUserScoreDTO.setAdd22(params.get("add22") + "");
            spUserScoreDTO.setAdd33(params.get("add33") + "");
            spUserScoreDTO.setAdd44(params.get("add44") + "");
            spUserScoreDTO.setAdd55(params.get("add55") + "");
            spUserScoreDTO.setAdd66(params.get("add66") + "");
            spUserScoreDTO.setAdd77(params.get("add77") + "");
            spUserScoreDTO.setAdd88(params.get("add88") + "");
            spUserScoreDTO.setAdd99(params.get("add99") + "");
            spUserScoreDTO.setAdd1010(params.get("add1010") + "");
            spUserScoreDTO.setSub11(params.get("sub11") + "");
            spUserScoreDTO.setSub22(params.get("sub22") + "");
            spUserScoreDTO.setSub33(params.get("sub33") + "");
            spUserScoreDTO.setSub44(params.get("sub44") + "");
            spUserScoreDTO.setSub55(params.get("sub55") + "");
            spUserScoreDTO.setSub66(params.get("sub66") + "");
            spUserScoreDTO.setSub77(params.get("sub77") + "");
            spUserScoreDTO.setSub88(params.get("sub88") + "");
            spUserScoreDTO.setSub99(params.get("sub99") + "");
            spUserScoreDTO.setSub1010(params.get("sub1010") + "");
            spUserScoreDTO.setMm2(params.get("mm2") + "");
            spUserScoreDTO.setSs2(params.get("ss2") + "");
            spUserScoreDTO.setMs2(params.get("ms2") + "");
            spUserScoreDTO.setNum(params.get("num") + "");
            spUserScoreDTO.setScore2(params.get("score2") + "");

            spUserScoreService.save(spUserScoreDTO);
            String type = (String) params.get("type");
            if("group".equals(type)) {
                // 修改成绩
                SpMatchItemTeamEntity team = spMatchItemTeamService.selectById(params.get("id").toString());
                Map<String, Object> tuParams = new HashMap<>();
                tuParams.put("matchItemTeamId", team.getId());
                List<SpMatchItemTeamUserEntity> list = spMatchItemTeamUserService.queryList(
                        new QueryWrapper<SpMatchItemTeamUserEntity>()
                                .eq("match_item_team_id", team.getId())
                                .eq("type", "1")
                );
                for(SpMatchItemTeamUserEntity user : list){
                    //第一轮
                    user.setScore(spUserScoreDTO.getScore());
                    user.setScore1(spUserScoreDTO.getSeconds());
                    user.setScore2(spUserScoreDTO.getNum());
                    //第二轮
                    user.setScore00(spUserScoreDTO.getScore2());
                    user.setScore11(spUserScoreDTO.getSeconds2());
                    user.setScore22(spUserScoreDTO.getNum());
                    user.setIsAutoScore("1");
                    spMatchItemTeamUserService.updateById(user);
                }
            }else {
                // 修改成绩
                String id = params.get("id").toString();
                SpMatchItemTeamUserEntity user = spMatchItemTeamUserService.selectById(id);
                //第一轮
                user.setScore(spUserScoreDTO.getScore());
                user.setScore1(spUserScoreDTO.getSeconds());
                user.setScore2(spUserScoreDTO.getNum());
                //第二轮
                user.setScore00(spUserScoreDTO.getScore2());
                user.setScore11(spUserScoreDTO.getSeconds2());
                user.setScore22(spUserScoreDTO.getNum());
                user.setIsAutoScore("1");
                spMatchItemTeamUserService.updateById(user);
            }
            return new Result<String>().ok("保存成功");
        }catch (Exception e){
            e.printStackTrace();
            return new Result<String>().error("保存失败");
        }
    }

}
